<script lang="ts" setup>
import type { DataType } from './types';

import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';

import { Page } from '@vben/common-ui';

import { Button, message, Modal } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteTag, getTag, postTagStatus } from '#/api/portal/tag';
import Icon from '#/components/Icons';
import { toggleStatus } from '#/utils';

defineOptions({
  name: 'PortalAdminVisit',
});

const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const viewTitle = routeMeta.title.replace('管理', '');

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: `请输入${viewTitle}`,
      },
      fieldName: 'keyword',
      label: `${viewTitle}名称`,
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};

const gridOptions: VxeGridProps<DataType> = {
  rowConfig: {
    isHover: true,
  },
  checkboxConfig: {
    labelField: 'name',
    highlight: true,
    range: true,
    checkMethod: ({ row }) => {
      return row.post_count === 0;
    },
  },
  columns: [
    { field: 'id', title: '编号' },
    { field: 'name', title: '标签名称', type: 'checkbox', align: 'left' },
    { field: 'post_count', title: '关联文章数量' },
    {
      field: 'status',
      title: '状态',
      cellRender: {
        name: 'CellStatus',
        props: {
          checkedChildren: '开启',
          checkedValue: 1,
          unCheckedChildren: '停用',
          unCheckedValue: 0,
          on: {
            change: (checked: any, row: any) => {
              if (row.post_count > 0) {
                message.info('此标签存在文章，不允许停用！');
                row.status = toggleStatus(checked);
                return;
              }
              Modal.confirm({
                title: '系统提示',
                content: `确认要${checked === 0 ? '停用' : '启用'}吗?`,
                async onOk() {
                  try {
                    await postTagStatus({
                      id: row.id,
                      status: checked,
                    });
                    message.success(`已${checked ? '启用' : '停用'}`);
                    row.status = checked;
                  } catch {
                    row.status = toggleStatus(checked);
                  }
                },
                onCancel() {
                  row.status = toggleStatus(checked);
                },
              });
            },
          },
        },
      },
    },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: '操作',
      width: 160,
    },
  ],
  height: 'auto',
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const { data } = await getTag({
          page: page.currentPage,
          limit: page.pageSize,
          ...formValues,
        });
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
  formOptions,
});

const handleDelete = async (row?: DataType) => {
  const $table = GridApi.grid;
  if ($table) {
    let ids: any = [];
    if (row?.id) {
      ids = [row.id];
    } else {
      const selectRows = $table.getCheckboxRecords();
      if (selectRows.length > 0) {
        ids = selectRows.map((item) => item.id);
      } else {
        message.error('未选择任何行');
      }
    }
    Modal.confirm({
      title: '系统提示',
      content: `确认要删除吗?`,
      async onOk() {
        const { msg } = await deleteTag({ ids });
        $table.remove(row);
        message.success(msg);
      },
    });
  }
};
</script>

<template>
  <Page auto-content-height>
    <Grid :table-title="`${viewTitle}列表`">
      <template #toolbar-tools>
        <Button class="mr-2" danger type="primary" @click="handleDelete()">
          <span class="anticon">
            <Icon icon="ri:delete-bin-line" />
          </span>
          删除
        </Button>
      </template>
      <template #action="{ row }">
        <Button
          :disabled="row.post_count > 0"
          danger
          type="primary"
          @click="handleDelete(row)"
        >
          <template #icon>
            <span class="anticon">
              <Icon icon="ri:delete-bin-line" />
            </span>
          </template>
          删除
        </Button>
      </template>
    </Grid>
  </Page>
</template>
